package com.yanwq.sayhi.controller.article.fragment;


import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanwq.pulltorefreshview.view.PullToLoadListener;
import com.yanwq.pulltorefreshview.view.PullToRefreshLayout;
import com.yanwq.pulltorefreshview.view.PullToRefreshListener;
import com.yanwq.pulltorefreshview.view.PullToRefreshRecyclerView;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseFragment;
import com.yanwq.sayhi.common.client.OkJsonArrayResponseCallback;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRequestParams;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.event.ArticleEvent;
import com.yanwq.sayhi.common.tool.SharedPrefTool;
import com.yanwq.sayhi.controller.article.activity.AudioAddActivity;
import com.yanwq.sayhi.controller.article.activity.PhotoAddActivity;
import com.yanwq.sayhi.controller.article.activity.TextAddActivity;
import com.yanwq.sayhi.controller.article.adapter.ArticleAdapter;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.controller.video.FFmpegRecordActivity;
import com.yanwq.sayhi.dao.bean.Article;
import com.yanwq.sayhi.widget.MToast;
import com.yanwq.sayhi.widget.SelectDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
public class ArticleListFragment extends BaseFragment {
    private SelectDialog<Integer> mFilterDialog;
    private SelectDialog<Integer> mSendDialog;

    @BindView(R.id.al_actionbar)
    View mVActionbar;
    @BindView(R.id.article_refresh)
    PullToRefreshLayout mRLayout;
    @BindView(R.id.article_list)
    PullToRefreshRecyclerView mRecyclerView;
    @BindView(R.id.mode_club)
    Button mIVModeClub;
    @BindView(R.id.new_count)
    Button mTVNewCount;

    @OnClick(R.id.al_filter)
    void filter(View view) {
        mFilterDialog.show();
    }

    @OnClick(R.id.al_send)
    void send(View view) {
        mSendDialog.show();
    }

    @OnClick(R.id.mode_club)
    void modeClub() {
        SharedPrefTool.putConfig("mode", null);
        SharedPrefTool.putConfig("clubName", null);
        SharedPrefTool.putConfig("clubId", 0);
        mIVModeClub.setVisibility(View.GONE);
        autoRefresh();
    }

    ArticleAdapter mAdapter;

    private int mPage;
    private int mSize;
    private int mType = -1;
    private long mRefreshTime;

    public ArticleListFragment() {
        // Required empty public constructor
    }

    public void setType(int type) {
        mType = type;
        autoRefresh();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_article_list, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @SuppressWarnings("unused")
    public void onEvent(ArticleEvent event) {
        switch (event.getEventType()) {
            case ArticleEvent.SEND_SUCCESS:
                autoRefresh();
                break;
            case ArticleEvent.MODE_CHANGE:
                refreshMode();
                autoRefresh();
                break;
            case ArticleEvent.TYPE_CHANGE:
                setType(event.getArticleType());
                break;
        }
    }

    private void refreshMode() {
        if ("club".equals(SharedPrefTool.getConfig("mode", ""))) {
            mIVModeClub.setVisibility(View.VISIBLE);
            mIVModeClub.setText(SharedPrefTool.getConfig("clubName", ""));
        }
    }

    @Override
    public void init() {
        mAdapter = new ArticleAdapter();
        mPage = 0;
        mSize = 20;
        mRefreshTime = System.currentTimeMillis();
    }

    @Override
    public void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        View header = LayoutInflater.from(getActivity()).inflate(R.layout.head_article_list, mRecyclerView, false);
        mAdapter.addHeader(header);
        mRecyclerView.setAdapter(mAdapter);

        post(new Runnable() {
            @Override
            public void run() {
                /*mVStatusBarShadow.getLayoutParams().height = ((BaseActivity) getActivity()).getStatusBarHeight();
                mVStatusBarShadow.requestLayout();*/

                mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                    int actionbarHeight = mVActionbar.getMeasuredHeight();
                    int currentHeight = actionbarHeight;

                    @Override
                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                        super.onScrolled(recyclerView, dx, dy);
                        currentHeight -= dy;

                        if (currentHeight < 0) {
                            currentHeight = 0;
                        } else if (currentHeight > actionbarHeight) {
                            currentHeight = actionbarHeight;
                        }

                        float alpha = (float) currentHeight / actionbarHeight;
                        mVActionbar.setAlpha(alpha);
                    }
                });
            }
        });

        mRLayout.setPullToRefreshListener(new PullToRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

        mRLayout.setPullToLoadListener(new PullToLoadListener() {
            @Override
            public void onLoad() {
                load();
            }
        });

        initMenu();
        refreshMode();
        loopRefreshCount();
        autoRefresh();
    }

    private void initMenu() {
        List<SelectDialog.Item<Integer>> filterList = new ArrayList<>();
        filterList.add(new SelectDialog.Item<>("重置", -1));
        filterList.add(new SelectDialog.Item<>("文本", 0));
        filterList.add(new SelectDialog.Item<>("图片", 1));
        filterList.add(new SelectDialog.Item<>("语音", 2));
        filterList.add(new SelectDialog.Item<>("视频", 3));
        mFilterDialog = new SelectDialog<>(getActivity(), filterList);
        mFilterDialog.setOnSelectedListener(new SelectDialog.OnSelectedListener<Integer>() {
            @Override
            public void onSelected(String item, Integer integer) {
                setType(integer);
            }
        });

        List<SelectDialog.Item<Integer>> sendList = new ArrayList<>();
        sendList.add(new SelectDialog.Item<>("文本", 0));
        sendList.add(new SelectDialog.Item<>("图片", 1));
        sendList.add(new SelectDialog.Item<>("语音", 2));
        sendList.add(new SelectDialog.Item<>("视频", 3));
        mSendDialog = new SelectDialog<>(getActivity(), sendList);
        mSendDialog.setOnSelectedListener(new SelectDialog.OnSelectedListener<Integer>() {
            @Override
            public void onSelected(String item, Integer integer) {
                Intent intent;
                switch (integer) {
                    case 0:
                        intent = new Intent(getActivity(), TextAddActivity.class);
                        startActivity(intent);
                        break;
                    case 1:
                        intent = new Intent(getActivity(), PhotoAddActivity.class);
                        startActivity(intent);
                        break;
                    case 2:
                        intent = new Intent(getActivity(), AudioAddActivity.class);
                        startActivity(intent);
                        break;
                    case 3:
                        intent = new Intent(getActivity(), FFmpegRecordActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });
    }

    private void autoRefresh() {
        post(new Runnable() {
            @Override
            public void run() {
                mRLayout.startRefresh();
            }
        }, 500);
    }

    private void loopRefreshCount() {
        post(refreshCountRun);
    }

    private Runnable refreshCountRun = new Runnable() {
        @Override
        public void run() {
            refreshCount();
        }
    };

    private void refreshCount() {
        String path = "/article/count";
        long clubId = SharedPrefTool.getConfig("clubId", 0);

        OkRequestParams params = new OkRequestParams();
        params.put("refreshTime", mRefreshTime);
        params.put("type", mType);

        if (clubId != 0) {
            path = "/article/count/club";
            params.put("clubId", clubId);
        }

        OkRestClient.getInstance().get(getActivity(), path, params, new OkJsonObjectResponseCallback() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                int count = jsonObject.getIntValue("msg");
                if (count > 0) {
                    mTVNewCount.setVisibility(View.VISIBLE);
                    mTVNewCount.setText(String.valueOf(count));
                } else {
                    mTVNewCount.setVisibility(View.GONE);
                }
            }

            @Override
            public void onStart() {
            }

            @Override
            public void onFail(int status, String s, Throwable throwable) {
            }

            @Override
            public void onStop() {
                if (isAdded()) {
                    post(refreshCountRun, 5000);
                }
            }
        });
    }

    private void refresh() {
        mPage = 0;
        OkRequestParams params = new OkRequestParams();
        params.put("page", mPage);
        params.put("size", mSize);
        params.put("type", mType);
        params.put("token", UserMgr.get().getToken());
        String path = "/article/list";

        if ("club".equals(SharedPrefTool.getConfig("mode", null))) {
            params.put("clubId", SharedPrefTool.getConfig("clubId", 0));
            path = "/article/list/club";
        }

        OkRestClient.getInstance().get(getActivity(),
                path,
                params,
                new OkJsonArrayResponseCallback() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(JSONArray jsonArray) {
                        //mTVNewCount.setVisibility(View.GONE);
                        List<Article> articleList = JSON.parseArray(jsonArray.toJSONString(),
                                Article.class);
                        mAdapter.refresh(articleList);

                        if (articleList.size() > 0) {
                            mRefreshTime = articleList.get(0).getPublishTime();
                        }
                    }

                    @Override
                    public void onStop() {
                        mRLayout.stopRefresh();
                    }
                });
    }

    private void load() {
        mPage++;
        OkRequestParams params = new OkRequestParams();
        params.put("page", mPage);
        params.put("size", mSize);
        params.put("type", mType);
        params.put("token", UserMgr.get().getToken());
        String path = "/article/list";

        if ("club".equals(SharedPrefTool.getConfig("mode", null))) {
            params.put("clubId", SharedPrefTool.getConfig("clubId", 0));
            path = "/article/list/club";
        }

        OkRestClient.getInstance().get(getActivity(),
                path,
                params,
                new OkJsonArrayResponseCallback() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(JSONArray jsonArray) {
                        List<Article> articleList = JSON.parseArray(jsonArray.toJSONString(),
                                Article.class);
                        mAdapter.load(articleList);
                    }

                    @Override
                    public void onStop() {
                        mRLayout.stopLoad();
                    }
                });
    }
}
